package cn.school.demo.repository

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import cn.school.demo.pojo.Article
import cn.school.demo.pojo.Result
import cn.school.demo.util.HttpApi
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.google.gson.reflect.TypeToken
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class SearchRepository {
    private val httpApi: HttpApi

    init {
        val retrofit =
            Retrofit.Builder().baseUrl(DataRepository.BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        httpApi = retrofit.create(HttpApi::class.java)
    }

    fun getTopSearchList(): LiveData<MutableList<Article>> {
        val responseLiveData = MutableLiveData<MutableList<Article>>()
        httpApi.getTopSearchList().enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    it.data["topSearch"]?.let {
                        try {
                            val topSearchList = GsonUtils.fromJson<MutableList<Article>>(
                                it.toString(),
                                object : TypeToken<MutableList<Article>>() {}.type
                            )
                            topSearchList?.let {
                                responseLiveData.value = it
                            } ?: LogUtils.e("获得热搜榜http返回值的topSearchList为空！！")
                        } catch (e: Error) {
                            LogUtils.e(e.printStackTrace())
                        }
                    } ?: LogUtils.e("获得热搜榜http返回值的data[`topSearch`]为空！！")
                } ?: LogUtils.e("获得热搜榜http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }

    fun getSearchedResultList(searchContext: String): LiveData<MutableList<Article>> {
        val responseLiveData = MutableLiveData<MutableList<Article>>()
        httpApi.getSearchedResultList(mapOf("search" to searchContext))
            .enqueue(object : Callback<Result> {
                override fun onResponse(call: Call<Result>, response: Response<Result>) {
                    response.body()?.let {
                        if (it.success) {
                            it.data["article"]?.let { jsonData ->
                                try {
                                    val articleList = GsonUtils.fromJson<MutableList<Article>>(
                                        jsonData.toString(),
                                        object : TypeToken<MutableList<Article>>() {}.type
                                    )
                                    articleList?.let {
                                        responseLiveData.value = articleList
                                    } ?: {
                                        LogUtils.e("搜索结果http返回值的data[\"article\"] is null!!")
                                        responseLiveData.value =
                                            mutableListOf(Article(articleName = response.body()!!.message))
                                    }
                                } catch (e: Error) {
                                    e.printStackTrace()
                                }
                            } ?: LogUtils.e("搜索结果http返回值的data为空！！")
                        } else {
                            LogUtils.e(it.message)
                            responseLiveData.value =
                                mutableListOf(Article(articleName = response.body()!!.message))
                        }
                    } ?: LogUtils.e("搜索结果http返回值为空！")
                }

                override fun onFailure(call: Call<Result>, t: Throwable) {
                    LogUtils.e(t)
                }
            })
        return responseLiveData
    }
}